package com.jin.webvideo.service;

import com.jin.webvideo.entity.ForbidRecord;
import com.jin.webvideo.mapper.AccessMapper;
import org.apache.http.conn.util.InetAddressUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class AccessServer {
    @Autowired
    private AccessMapper accessMapper;


    public List<ForbidRecord> findRecordByUser(String user, long time, String forbidType) {
        return accessMapper.findRecordByKey(user, time, ForbidRecord.TYPE_USER, forbidType);
    }

    public List<ForbidRecord> findRecordBySpecificAddress(String specificAddress, long time) {
        if (InetAddressUtils.isIPv4Address(specificAddress)) {
            return accessMapper.findRecordByAddress(specificAddress, time, ForbidRecord.TYPE_INET4ADDRESS, ForbidRecord.FORBID_TYPE_PATH);
        }
        if (InetAddressUtils.isIPv6Address(specificAddress)) {
            return accessMapper.findRecordByAddress(specificAddress, time, ForbidRecord.TYPE_INET6ADDRESS, ForbidRecord.FORBID_TYPE_PATH);
        }
        return new ArrayList<>();
    }

    /**
     * 由于封禁具有时效性，只管插入就行了
     * ip地址 对路径的访问权限进行封禁/延长封禁
     * @param specificAddress
     * @param path
     * @param second
     * @param information
     * @return
     */
    public ForbidRecord forbidPathForAddress(String specificAddress, String path, long second, String information) {
        String forbidType = ForbidRecord.TYPE_INET4ADDRESS;
        if (InetAddressUtils.isIPv6Address(specificAddress)) {
            forbidType = ForbidRecord.TYPE_INET6ADDRESS;
        }
        ForbidRecord record = new ForbidRecord(second, information, forbidType, specificAddress);
        record.setForbidType(ForbidRecord.FORBID_TYPE_PATH);
        record.setVal("/*");
        accessMapper.addRecord(record);
        return record;
    }

    public ForbidRecord forbidAddress(String specificAddress, long second, String information) {
        return forbidPathForAddress(specificAddress, ForbidRecord.PATH_ALL, second, information);
    }
}
